package com.yylending.las.lending.process.supplyinfo;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.common.form.FormRow;
import com.yyfax.common.form.FormSelectView;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.SoftKeyboardUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.common.utils.area.AddressCityBean;
import com.yylending.las.common.utils.area.AddressDistrictBean;
import com.yylending.las.common.utils.area.AddressProvinceBean;
import com.yylending.las.common.utils.area.LocalAreaManager;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.common.widgets.pickerview.view.OptionsPickerView;
import com.yylending.las.common.widgets.pickerview.view.TimePickerView;
import com.yylending.las.deviceinfo.UploadDeviceService;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoPresenter;
import com.yylending.las.lending.quota.entity.CustomerBean;
import com.yylending.las.lending.quota.entity.OptionBean;
import com.yylending.las.lending.quota.entity.OptionsUtil;
import com.yylending.las.lending.quota.initdata.InitDataModel;
import com.yylending.las.lending.quota.initdata.InitDataPresenter;

import java.util.ArrayList;
import java.util.Date;


/**
 * 补充资料
 */
public class SupplementInfoFragment extends BaseFragment implements SupplementInfoPresenter.View, InitDataPresenter.View, LocationPresenter.View,
		CustomerInfoPresenter.View, FormSelectView.onDrawableClickListener, OptionsPickerView.OnOptionsSelectListener {

	@BindView(R.id.choose_work_start_time_fr)
	FormRow mChooseWorkStartTimeFr;
	@BindView(R.id.choose_company_address_fr)
	FormRow mChooseCompanyAddressFr;
	@BindView(R.id.company_detail_address_fr)
	FormRow mCompanyDetailAddressFr;
	@BindView(R.id.region_code_edt)
	EditText mRegionCodeEdt;
	@BindView(R.id.phone_number_edt)
	EditText mPhoneNumberEdt;
	@BindView(R.id.residential_address_fr)
	FormRow mResidentialAddressFr;
	@BindView(R.id.detailed_address_fr)
	FormRow mDetailedAddressFr;
	@BindView(R.id.family_phone_fr)
	FormRow mFamilyPhoneFr;
	@BindView(R.id.family_name_fr)
	FormRow mFamilyNameFr;
	@BindView(R.id.relation_fr)
	FormRow mRelationFr;
	@BindView(R.id.extension_phone_edt)
	EditText mExtensionPhoneEdt;

	private static final String TAG = SupplementInfoFragment.class.getSimpleName();
	private static final int REQUEST_CONTACT = 88;
	private static final int COMPANY_ADDRESS = 89;
	private static final int RESIDENTIAL_ADDRESS = 90;
	private static final int LOADER_ID_SUPPLEMENT_INFO = 91;
	private static final int LOADER_ID_INIT_DATA = 92;
	private static final int LOADER_ID_LOCATE = 93;
	private static final int LOADER_ID_CUSTOMER_INFO = 94;
	/** 区集合 */
	private ArrayList<ArrayList<ArrayList<AddressDistrictBean>>> mDistrictList;
	/** 城市集合 */
	private ArrayList<ArrayList<AddressCityBean>> mCityList;
	/** 省份集合 */
	private ArrayList<AddressProvinceBean> mProvinceList;
	/** 地址选择器 */
	private OptionsPickerView mCompanyAddressPv;
	/** 时间选择器 */
	private TimePickerView mHireDatePicker;
	/** 关系选择器 */
	private OptionsPickerView mRelationPicker;
	/** 已选择的关系 */
	private OptionBean mSelectedRelation;
	/** 地址选择器类型，包括公司地址、居住地址*/
	private int addressType;
	/** 关系对象集合 */
	private ArrayList<OptionBean> mRelationList = new ArrayList<>();
	/** 关系编号 */
	private String mGetRelationNo;
	/** 关系对象 */
	private OptionBean mGetRelation;
	/** 保存用户附加信息的请求参数 */
	private SupplementInfoModel.SupplyInfo mSaveInfoParams = new SupplementInfoModel.SupplyInfo();
	/** 定位信息 */
	private Location mLocation;
	private SupplementInfoPresenter mSupplementInfoPresenter;
	private InitDataPresenter mInitDataPresenter;
	private LocationPresenter mLocatePresenter;

	private CustomerInfoPresenter mCustomerInfoPresenter;

	Unbinder mUnbind;

	public static BaseFragment newInstance() {
		BaseFragment fragment = new SupplementInfoFragment();
		return fragment;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_supplement_info, null);
		mUnbind = ButterKnife.bind(this, view);
		return view;

	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		((FormSelectView) mFamilyPhoneFr.getRightView()).setonDrawableClickListener(this);
		Context context = getContext();
		mProvinceList = LocalAreaManager.getInstance(context).mProvinceList;
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_SUPPLEMENT_INFO, null, this);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_INIT_DATA, null, this);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_CUSTOMER_INFO, null, this);
	}

	@Override
	public void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbind.unbind();
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_SUPPLEMENT_INFO);
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_INIT_DATA);
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_CUSTOMER_INFO);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_INIT_DATA:
				if (null == mInitDataPresenter) {
					mInitDataPresenter = (InitDataPresenter) data;
					mInitDataPresenter.attach(this);
					mInitDataPresenter.getOptionList();
				}
				break;
			case LOADER_ID_SUPPLEMENT_INFO:
				if (null == mSupplementInfoPresenter) {
					mSupplementInfoPresenter = (SupplementInfoPresenter) data;
					mSupplementInfoPresenter.attach(this);
				}
				break;
			case LOADER_ID_LOCATE:
				if (null == mLocatePresenter) {
					mLocatePresenter = (LocationPresenter) data;
					mLocatePresenter.attach(this);
					PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mPermissionsGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				}
				break;
			case LOADER_ID_CUSTOMER_INFO:
				if (null == mCustomerInfoPresenter) {
					mCustomerInfoPresenter = (CustomerInfoPresenter) data;
					mCustomerInfoPresenter.attach(this);
					mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_ADDINFO);
				}
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_INIT_DATA:
				return new PresenterLoader<>(getActivity(), new InitDataPresenter.Generator());
			case LOADER_ID_SUPPLEMENT_INFO:
				return new PresenterLoader<>(getActivity(), new SupplementInfoPresenter.Generator());
			case LOADER_ID_CUSTOMER_INFO:
				return new PresenterLoader<>(getActivity(), new CustomerInfoPresenter.Generator());
			default:
				break;
		}
		return null;
	}

	/**
	 * 更新与本人关系的FormRow
	 */
	private void setRelationFr() {
		mGetRelation = OptionsUtil.getOptionBeanByValue(mRelationList, mGetRelationNo);
		if (null != mGetRelation) {
			mRelationFr.setText(mGetRelation.itemName);
		}
	}

	@Override
	public void customerInfoExist(String type, CustomerBean customerBean) {
		if (Constants.CUSTOMER_TYPE_ADDINFO.equals(type)) {
			SupplementInfoModel.SupplyInfo supplyInfo = customerBean.addInfo;
			mGetRelationNo = supplyInfo.familyRelation;
			setRelationFr();
			//获取的是时间戳
			mChooseWorkStartTimeFr.setText(TimeUtils.formatDateTimeSlash(Long.valueOf(supplyInfo.workStart)));
			mSaveInfoParams.workStart = supplyInfo.workStart;
			//兼容以前的旧数据
			if(mChooseWorkStartTimeFr.getText().toString().equals("1970/01/01")){
				mSaveInfoParams.workStart="28800000";
			}
			mCompanyDetailAddressFr.setText(supplyInfo.comAddS);
			mDetailedAddressFr.setText(supplyInfo.liveAddS);
			mFamilyNameFr.setText(supplyInfo.familyName);
			mFamilyPhoneFr.setText(supplyInfo.familyPhone);
			mRegionCodeEdt.setText(supplyInfo.comPhoneD);
			mPhoneNumberEdt.setText(supplyInfo.comPhoneN);
			mExtensionPhoneEdt.setText(supplyInfo.comPhoneS);

			mSaveInfoParams.comAddP = supplyInfo.comAddP;
			mSaveInfoParams.comAddC = supplyInfo.comAddC;
			mSaveInfoParams.comAddD = supplyInfo.comAddD;
			mSaveInfoParams.liveAddP = supplyInfo.liveAddP;
			mSaveInfoParams.liveAddC = supplyInfo.liveAddC;
			mSaveInfoParams.liveAddD = supplyInfo.liveAddD;
			String compayAddress = LocalAreaManager.getInstance().getProvinceAndCityName(supplyInfo.comAddP, supplyInfo.comAddC, supplyInfo.comAddD);
			String liveAddress = LocalAreaManager.getInstance().getProvinceAndCityName(supplyInfo.liveAddP, supplyInfo.liveAddC, supplyInfo.liveAddD);
			mChooseCompanyAddressFr.setText(compayAddress);
			mResidentialAddressFr.setText(liveAddress);
		}
	}

	@Override
	public void customerInfoNotExist(String type, String msg) {
		// TODO: 2017/7/24 附加信息不存在
		if (Constants.CUSTOMER_TYPE_ADDINFO.equals(type)) {

		}
	}

	@Override
	public void getCustomerInfoError(String type, String msg) {
		// TODO: 2017/7/24 返回异常
		if (Constants.CUSTOMER_TYPE_ADDINFO.equals(type)) {

		}
	}

	@Override
	public void initOptionsSuccess(InitDataModel.Options options) {
		if (options.relation.size() > 0) {
			mRelationList.clear();
			mRelationList.addAll(options.relation);
			setRelationFr();
		}

	}

	@Override
	public void initOptionsFail(String msg) {
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CONTACT && resultCode == Activity.RESULT_OK && data != null) {
			Uri result = data.getData();
			String[] contact = getPhoneContacts(result);
			if (contact != null && contact[0] != null && contact[1] != null) {
				//mFamilyNameFr.setText(contact[0]);
				mFamilyPhoneFr.setText(contact[1].replace(" ", "").replace("-", "").replace("+86", ""));
			}
		}
	}

	/**
	 * 获取已选择的联系人信息
	 */
	private String[] getPhoneContacts(Uri uri) {
		String[] contact = new String[2];
		try {
			//得到ContentResolver对象
			ContentResolver cr = getActivity().getContentResolver();
			//取得电话本中开始一项的光标
			Cursor cursor = cr.query(uri, null, null, null, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					//取得联系人名字
					int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
					contact[0] = cursor.getString(nameFieldColumnIndex);
					//取得电话号码
					String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
					Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);

					if (phone != null) {
						phone.moveToFirst();
						contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					}
					phone.close();
					cursor.close();
				} else {
					showPermissionDialog();
				}
			} else {
				showPermissionDialog();
				CLog.i(TAG, "get Contacts is fail");
			}
		} catch (Exception e) {
			CLog.e(TAG, e.getMessage());
		}
		return contact;
	}

	private void showPermissionDialog(){
		showTwoBtnDialog(R.string.read_contacts_permission_hint, R.string.confirm, R.string.cancel, new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	@OnClick({R.id.choose_work_start_time_fr, R.id.choose_company_address_fr, R.id.residential_address_fr, R.id.relation_fr, R.id.next_step_btn, R.id.family_phone_fr})
	public void OnClick(View v) {
		switch (v.getId()) {
			case R.id.choose_work_start_time_fr:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				showChooseTime();
				break;
			case R.id.choose_company_address_fr:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				addressType = COMPANY_ADDRESS;
				showAddressPicker(getString(R.string.select_company_address));
				break;
			case R.id.residential_address_fr:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				addressType = RESIDENTIAL_ADDRESS;
				showAddressPicker(getString(R.string.select_living_address));
				break;
			case R.id.relation_fr:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				showRelationShipOptions();
				break;
			case R.id.next_step_btn:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_ADDITIONAL_INFORMATION);
				if (validate()) {
					requestPermission();
					saveInfo();
				}
				break;
			case R.id.family_phone_fr:
				go2SelectPhone();
				break;
			default:
				break;
		}
	}

	/**
	 * 保存补充资料的信息
	 */
	private void saveInfo() {
		mSaveInfoParams.comAddS = mCompanyDetailAddressFr.getText();
		mSaveInfoParams.liveAddS = mDetailedAddressFr.getText();
		mSaveInfoParams.familyName = mFamilyNameFr.getText();
		mSaveInfoParams.familyPhone = mFamilyPhoneFr.getText();
		mSaveInfoParams.familyRelation = (null == mGetRelation ? mSelectedRelation.itemNo : mGetRelation.itemNo);
		mSaveInfoParams.comPhoneD = mRegionCodeEdt.getText().toString();
		mSaveInfoParams.comPhoneN = mPhoneNumberEdt.getText().toString();
		mSaveInfoParams.comPhoneS = mExtensionPhoneEdt.getText().toString();
		mSupplementInfoPresenter.saveSupplyInfo(mSaveInfoParams);
	}


	@Override
	public void saveSupplyInfoSuccess() {
		((ProcessActivity) getActivity()).pageDown();
	}

	@Override
	public void saveSupplyInfoFailure(String tips) {
		showToast(tips);
	}

	/**
	 * 检查内容是否合法
	 */
	private boolean validate() {
		if (!mChooseWorkStartTimeFr.validate()) { //入职时间
			return false;
		}
		if (!mChooseCompanyAddressFr.validate()) { //公司地址
			return false;
		}
		if (!mCompanyDetailAddressFr.validate()) { //公司详细地址
			return false;
		}

		String areaCode = mRegionCodeEdt.getText().toString();
		String phoneCode = mPhoneNumberEdt.getText().toString();

		if (TextUtils.isEmpty(areaCode) || TextUtils.isEmpty(phoneCode)) {
			showToast(String.format(getString(R.string.please_input_toast), getString(R.string.company_phone)));
			return false;
		}

		if (phoneCode.length() != 11) {
			if (areaCode.length() < 3) {
				showToast(String.format(getString(R.string.please_input_correct), getString(R.string.area_code)));
				return false;
			}
			if (phoneCode.length() < 7) {
				showToast(String.format(getString(R.string.please_input_correct), getString(R.string.tel_or_mobilePhone_number)));
				return false;
			}
		}

		if (!mResidentialAddressFr.validate()) { // 居住地址
			return false;
		}
		if (!mDetailedAddressFr.validate()) { // 居住详细地址
			return false;
		}
		if (!mFamilyPhoneFr.validate()) { // 家属电话
			return false;
		}
		if (!RegexUtil.isMobileNumber(mFamilyPhoneFr.getText())) {
			showToast("家属电话只支持手机号");
			return false;
		}
		if (!mFamilyNameFr.validate()) { //  家属姓名
			return false;
		}
		if (!mRelationFr.validate()) { // 与本人关系
			return false;
		}

		return true;
	}

	/**
	 * 弹出地址选择器
	 */
	private void showAddressPicker(String title) {
		if (mCompanyAddressPv == null) {

			Context context = getContext();
			mCityList = LocalAreaManager.getInstance(context).mCityList;
			mDistrictList = LocalAreaManager.getInstance(context).mDistrictList;
			int chooseProvinceIndex = LocalAreaManager.getInstance(context).provinceIndex;
			int chooseCityIndex = LocalAreaManager.getInstance(context).cityIndex;
			int chooseDistrictIndex = LocalAreaManager.getInstance(context).districtIndex;

			mCompanyAddressPv = new OptionsPickerView(getActivity());
			mCompanyAddressPv.setPicker(mProvinceList, mCityList, mDistrictList, true);
			mCompanyAddressPv.setTitle(title);
			mCompanyAddressPv.setCyclic(false, false, false);
			mCompanyAddressPv.setCancelable(true);
			mCompanyAddressPv.setSelectOptions(chooseProvinceIndex, chooseCityIndex, chooseDistrictIndex);
			mCompanyAddressPv.setOnoptionsSelectListener(this);
		}
		mCompanyAddressPv.show();
	}

	@Override
	public void onOptionsSelect(int options1, int option2, int options3) {
		AddressProvinceBean companyProvince = mProvinceList.get(options1);
		AddressCityBean companyCity = mCityList.get(options1).get(option2);
		AddressDistrictBean companyDistrict = null;
		if (companyCity.getCounties().size() != 0) {
			companyDistrict = mDistrictList.get(options1).get(option2).get(options3);
		}
		String tx = companyProvince.getPickerViewText() + companyCity.getPickerViewText();
		String addD = "";
		if (null != companyDistrict) {
			addD = companyDistrict.getAreaId();
			tx += companyDistrict.getPickerViewText();
		}
		if (addressType == COMPANY_ADDRESS) {
			mSaveInfoParams.comAddP = companyProvince.getAreaId();
			mSaveInfoParams.comAddC = companyCity.getAreaId();
			mSaveInfoParams.comAddD = addD;
			mChooseCompanyAddressFr.setText(tx);
			mRegionCodeEdt.setText(mCityList.get(options1).get(option2).areaCode);
		} else {
			mSaveInfoParams.liveAddP = companyProvince.getAreaId();
			mSaveInfoParams.liveAddC = companyCity.getAreaId();
			mSaveInfoParams.liveAddD = addD;
			mResidentialAddressFr.setText(tx);
		}
	}

	/**
	 * 弹出时间选择器
	 */
	private void showChooseTime() {
		if (mHireDatePicker == null) {
			mHireDatePicker = new TimePickerView(getContext(), TimePickerView.Type.YEAR_MONTH_DAY);
			mHireDatePicker.setStartYear(1970);
			mHireDatePicker.setTime(new Date());
			mHireDatePicker.setCyclic(false);
			mHireDatePicker.setCancelable(true);
			// 时间选择后回调
			mHireDatePicker.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

				@Override
				public void onTimeSelect(Date date) {
					Date currentDate = new Date();
					if (currentDate.getTime() < date.getTime()) {
						showToast(R.string.date_select_error);
					} else {
						mChooseWorkStartTimeFr.setText(TimeUtils.formatDateTimeSlash(date));
						mSaveInfoParams.workStart = String.valueOf(date.getTime());
						CLog.i(TAG,"workStart---"+date.getTime());
					}
				}
			});
		}
		mHireDatePicker.show();
	}

	/**
	 * 选择关系状况
	 */
	public void showRelationShipOptions() {
		if (mRelationList.size() > 0) {
			if (null == mRelationPicker) {
				mRelationPicker = new OptionsPickerView(getActivity());
				mRelationPicker.setPicker(mRelationList);
				mRelationPicker.setTitle(getString(R.string.select_relationship));
				mRelationPicker.setCyclic(false, false, false);
				mRelationPicker.setCancelable(true);
				mRelationPicker.setSelectOptions(0, 0, 0);
				mRelationPicker.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

					@Override
					public void onOptionsSelect(int options1, int option2, int options3) {
						mSelectedRelation = mRelationList.get(options1);
						String tx = mSelectedRelation.getPickerViewText();
						mRelationFr.setText(tx);
					}
				});
			}
			mRelationPicker.show();
		} else {
			showToast(R.string.get_data_failed);
		}
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mPermissionsGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			if (permission.granted) {
				switch (permission.name) {
					case Manifest.permission.READ_CONTACTS:
						//忽略手势密码
						Global.setThirdPartyPageOpenedFlag(true);
						Intent intent = new Intent();
						intent.setAction(Intent.ACTION_PICK);
						intent.setData(ContactsContract.Contacts.CONTENT_URI);
						startActivityForResult(intent, REQUEST_CONTACT);
						break;
					case Manifest.permission.ACCESS_COARSE_LOCATION:
						mLocatePresenter.startLocation(false);
						break;
					default:
						break;
				}
			} else if (!permission.shouldShowRequestPermissionRationale) {
				showOneBtnDialog(getString(R.string.contact_right_hint, getString(R.string.app_name)));
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private PermissionsGrantedHelper.PermissionsGrantedListener mUploadGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			if (permission.granted) {
				switch (permission.name) {
					case Manifest.permission.READ_CONTACTS:
						startUploadService(Constants.EVALPATH_CONTACT);
						break;
					case Manifest.permission.READ_PHONE_STATE:
						startUploadService(Constants.EVALPATH_SOFTWARE);
						break;
					case Manifest.permission.READ_SMS:
						startUploadService(Constants.EVALPATH_SMS);
						break;
					case Manifest.permission.READ_CALL_LOG:
						startUploadService(Constants.EVALPATH_CALL);
						break;
					default:
						break;
				}
			} else if (!permission.shouldShowRequestPermissionRationale) {
				showOneBtnDialog(getString(R.string.contact_right_hint, getString(R.string.app_name)));
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void startUploadService(String evalPath){
		Intent intent = new Intent(getActivity().getApplicationContext(), UploadDeviceService.class);
		intent.putExtra(Constants.EVALPATH, evalPath);
		if (null != mLocation) {
			intent.putExtra(Constants.LONGITUDE, String.valueOf(mLocation.longitude));
			intent.putExtra(Constants.LATITUDE, String.valueOf(mLocation.latitude));
		}else{
			intent.putExtra(Constants.LONGITUDE, String.valueOf(Global.mLongitude));
			intent.putExtra(Constants.LATITUDE, String.valueOf(Global.mLatitude));
		}
		getActivity().startService(intent);
	}

	public boolean dismiss() {
		boolean isShowing = false;
		if (mRelationPicker != null && mRelationPicker.isShowing()) {
			isShowing = true;
			mRelationPicker.dismiss();
		}

		if (mHireDatePicker != null && mHireDatePicker.isShowing()) {
			isShowing = true;
			mHireDatePicker.dismiss();
		}

		if (mCompanyAddressPv != null && mCompanyAddressPv.isShowing()) {
			isShowing = true;
			mCompanyAddressPv.dismiss();
		}
		return isShowing;
	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
	}

	@Override
	public void onLocateFail(boolean noPermission) {

	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	@Override
	public void onDrawableClick(View view) {
		go2SelectPhone();
	}

	private void go2SelectPhone(){
		PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mPermissionsGrantedListener, Manifest.permission.READ_CONTACTS);
	}

	private void requestPermission() {
		PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mUploadGrantedListener, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.READ_CALL_LOG);
	}
}